import store from '@/store'
import VabProgress from 'nprogress'
import { wsUrl } from '@/config'
import Vue from 'vue'
import router from '@/router'

const token = store.getters['user/token']
let ws = null
let webscoket_data = null
let timer = null
let weboscket_callback = null
let webscoket_time = 5000 // 心跳链接时间
let loading = null
// 心跳长链参数
let heartbeat_data = {
  code: -1,
  token: token,
}
// 操作成功文案，匹配上就重新心跳链接
const messageList = [
  '开卡成功',
  '充值成功',
  '划出成功',
  '卡片冻结成功!',
  '卡片恢复成功!',
  '销卡成功',
]
//获取 websocket 推送的数据
let websocketonmessage = (e) => {
  // console.log('11111', e)
  const data = JSON.parse(e.data)
  if (data.code === -1) {
    timer = setTimeout(() => {
      sendData(heartbeat_data, weboscket_callback)
    }, webscoket_time)
  } else if (data.code === 0) {
    if (data.msg === '连接断开,token验证失败') {
      // loginOut()
      closewebsocket()
      // store.dispatch('user/logout')
    } else {
      Vue.prototype.$baseNotify(data.msg, '提示', 'error', 'top-right')
      clearInterval(timer)
      sendData(heartbeat_data, weboscket_callback)
    }
  } else if (data.code === 1) {
    if (data.msg === '连接成功,请先传token') {
      sendData(
        {
          code: 1,
          token: token,
        },
        weboscket_callback
      )
    } else if (messageList.includes(data.msg)) {
      console.log({ data })
      Vue.prototype.$baseNotify(data.msg, '提示', 'success', 'top-right')
      clearInterval(timer)
      sendData(heartbeat_data, weboscket_callback)
      return weboscket_callback()
    }
  } else if (
    data.code === 8051 ||
    data.code === 8011 ||
    data.code === 8151 ||
    data.code === 8111 ||
    data.code === 8211
  ) {
    clearInterval(timer)
    // Vue.prototype.$baseNotify('批量开卡中', '提示', 'success', 'top-right')
    VabProgress.start()
    // console.log(data)
    store.dispatch('ws/setMsgInfo', data)
    store.dispatch('ws/setShowProgressStatus', true)
    router.push('/home')
    // 批量开卡中
  } else if (
    data.code === 8052 ||
    data.code === 8012 ||
    data.code === 8152 ||
    data.code === 8112 ||
    data.code === 8212
  ) {
    VabProgress.done()
    store.dispatch('ws/setMsgInfo', data)
    setTimeout(() => {
      store.dispatch('ws/setShowProgressStatus', false)
    }, 1000)
    if (data.is_complete == 1) {
      Vue.prototype.$baseNotify(data.title, '提示', 'success', 'top-right')
      router.push('/Horoscope-card/prepaidCard')
    }
    clearInterval(timer)
    sendData(heartbeat_data, weboscket_callback)
    return weboscket_callback()
  }
}

// 连接成功
let websocketonopen = () => {
  // webscoket_data = {
  //     code: -1,
  //     token: token,
  // };
  // console.log("连接 websocket 成功");
}

// 连接失败时重新连接
let websocketonerror = () => {
  initWebSocket()
}

// 断开链接后报错
let websocketclose = (e) => {
  // Vue.prototype.$baseNotify(
  //   '链接断开，请重新提交！',
  //   '提示',
  //   'warning',
  //   'top-right'
  // )
  clearInterval(timer)
  // 重连
  sendData(webscoket_data, weboscket_callback)
  VabProgress.done()
  store.dispatch('ws/setShowProgressStatus', false)
}
// 手动关闭 websocket
let closewebsocket = () => {
  ws ? ws.close(1000) : ''
}

let initWebSocket = () => {
  //初始化 websocket
  let wsurl = wsUrl
  if (!window.WebSocket) {
    Vue.prototype.$baseNotify({
      message: '您的浏览器不支持websocket,请升级或更换浏览器！',
      type: 'error',
      center: true,
    })
    return
  }
  ws = new WebSocket(wsurl)
  ws.onmessage = websocketonmessage
  ws.onopen = websocketonopen
  ws.onerror = websocketonerror
  ws.onclose = websocketclose
}

// 发送数据
let sendData = (data, callback) => {
  webscoket_data = data //利用用户id+传递字段构成唯一参数（根据自己项目需求而定）
  weboscket_callback = callback
  //  判断 data 数据类型
  if (!(typeof data == 'string')) {
    data = JSON.stringify(data)
  }
  //  判断 websocket 的状态
  if (ws && ws.readyState === ws.OPEN) {
    clearInterval(timer)
    // 已经打开,可以直接发送
    ws.send(data)
  } else if (ws && ws.readyState === ws.CONNECTING) {
    clearInterval(timer)
    // 正在开启状态中,则 1 秒后重新发送
    if (JSON.parse(data).token) {
      setTimeout(() => {
        ws.send(data)
      }, 1000)
    }
  } else {
    // 未打开，则开启后重新调用
    initWebSocket()
    sendData(data, callback)
  }
}
// 导出
export { initWebSocket, sendData, closewebsocket, ws }
